|
1
|
|
|
import { FC, useEffect } from 'react'; |
|
2
|
|
|
import { pipe } from 'ramda'; |
|
3
|
|
|
import { CreateVisit } from '../../visits/types'; |
|
4
|
|
|
import { MercureInfo } from '../reducers/mercureInfo'; |
|
5
|
|
|
import { bindToMercureTopic } from './index'; |
|
6
|
|
|
|
|
7
|
|
|
export interface MercureBoundProps { |
|
8
|
|
|
createNewVisits: (createdVisits: CreateVisit[]) => void; |
|
9
|
|
|
loadMercureInfo: Function; |
|
10
|
|
|
mercureInfo: MercureInfo; |
|
11
|
|
|
} |
|
12
|
|
|
|
|
13
|
|
|
export function boundToMercureHub<T = {}>( |
|
14
|
|
|
WrappedComponent: FC<MercureBoundProps & T>, |
|
15
|
|
|
getTopicForProps: (props: T) => string, |
|
16
|
|
|
) { |
|
17
|
9 |
|
const pendingUpdates = new Set<CreateVisit>(); |
|
18
|
|
|
|
|
19
|
9 |
|
return (props: MercureBoundProps & T) => { |
|
20
|
13 |
|
const { createNewVisits, loadMercureInfo, mercureInfo } = props; |
|
21
|
13 |
|
const { interval } = mercureInfo; |
|
22
|
|
|
|
|
23
|
13 |
|
useEffect(() => { |
|
24
|
2 |
|
const onMessage = (visit: CreateVisit) => interval ? pendingUpdates.add(visit) : createNewVisits([ visit ]); |
|
25
|
|
|
const closeEventSource = bindToMercureTopic(mercureInfo, getTopicForProps(props), onMessage, loadMercureInfo); |
|
26
|
|
|
|
|
27
|
2 |
|
if (!interval) { |
|
28
|
|
|
return closeEventSource; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
const timer = setInterval(() => { |
|
32
|
|
|
createNewVisits([ ...pendingUpdates ]); |
|
33
|
|
|
pendingUpdates.clear(); |
|
34
|
|
|
}, interval * 1000 * 60); |
|
35
|
|
|
|
|
36
|
|
|
return pipe(() => clearInterval(timer), () => closeEventSource?.()); |
|
37
|
|
|
}, [ mercureInfo ]); |
|
38
|
|
|
|
|
39
|
13 |
|
return <WrappedComponent {...props} />; |
|
40
|
|
|
}; |
|
41
|
|
|
} |
|
42
|
|
|
|